<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------
namespace app\portal\controller;

use app\admin\model\CodePasswordModel;
use app\admin\model\MessageModel;
use app\admin\model\MoneyInfoModel;
use app\admin\model\OrderModel;
use app\admin\validate\AddMessageValidate;
use app\portal\model\UserModel;
use app\portal\validate\AddOrderValidate;
use app\portal\validate\BayValidate;
use cmf\controller\HomeBaseController;
use think\Db;

class IndexController extends HomeBaseController
{
    public function index()
    {
        $this->view->pay_all_type = config('pay_all_type');
        $this->view->s_all = $this->getRanS();//获取随机客服

        //验证是不是购买页面
        $this->view->shop_name = $shop_name = explode('.', $_SERVER['HTTP_HOST'])[0];
        $this->view->shop_info = $shop_info = UserModel::where(function ($req) use($shop_name) {
            $shop_id = input('shop_id/n');
            if(!$shop_id){
                return $req->where('domain', $shop_name);
            }else{
                return $req->where('id', $shop_id);
            }
        })
        ->where(['admin_audit' => 1, 'user_status' => ['neq', 0]])
        ->find();
        if ($shop_info) {

            //显示商家名称
            if(!empty($shop_info['user_nickname'])){
                $this->assign('basics_title',$shop_info['user_nickname']);
            }

            //显示购买信息
            $this->assign('shop_info', $shop_info);
            $this->assign('location_this', $_SERVER['HTTP_HOST']);
            //获取卖那些类型的产品
            $goods_type = Db::name('shop_goods')
                ->alias('shop_goods')
                ->where('shop_goods.user_id', $shop_info['id'])/*当前商家的产品*/
                ->where('shop_goods.shop_goods_state', 1)/*这个产品上架了*/
                ->join('goods goods', 'shop_goods.goods_id = goods.g_id and goods.delete_time is null')/*链接产品表*/
                ->join('nav_menu nav', 'goods.parent_id = nav.id')
                ->group('nav.id')
                ->field('nav.*')
                ->select();

            $this->assign('goods_type', $goods_type);

            return $this->fetch('bay');
        }

        $close_time = [
            strtotime(date('Y-m-d', strtotime('-1  days')))
            , strtotime(date('Y-m-d', strtotime('-2  days')))
            , strtotime(date('Y-m-d', strtotime('-3  days')))
            , strtotime(date('Y-m-d', strtotime('-4  days')))

        ];
        $this->assign('close_time', $close_time);



        return $this->fetch(':index');
    }

    //联系我们
    public function contact()
    {
        $this->view->s_all3 = $this->getRanS(3);
        $this->view->s_all = $this->getRanS();
        return $this->fetch(':contact');
    }


    //查询订单
    public function selectOrder()
    {
        $this->view->s_all = $this->getRanS();//获取随机客服
        $where = [];
        $select_type = 'phone';
        if ($val = input('orderNumber')) {
            //单号查询
            $where['order_number'] = $val;
            $select_type = 'order_number';
        }
        elseif ($val = input('phone')) {
            //联系方式查询
            $where['phone'] = $val;

        }
        $this->assign('select_type', $select_type);

        $this->assign('input_val', $val);


        if (count($where) > 0) {
            //开始查询
            $order_id = OrderModel::where($where)
                ->field('order_id')
                ->whereTime('update_time', 'month')/*本月的订单*/
                ->where('order_status', 2)/*已支付的*/
                ->select()->toArray();
            $order_id = array_column($order_id, 'order_id');
            /*获取订单*/
            $code_list = Db::name('code_password')
                ->where('pay_state', 1)/*已支付的*/
                ->whereIn('order_id', implode(',', $order_id))/*查询的订单*/
                ->select();
        }
        else {
            $code_list = [];
        }
        $this->assign('code_list', $code_list);
        return $this->fetch();
    }

    //获取下级产品
    public function getGoods()
    {
        $user_id = input('user_id/n');/*会员id*/
        $goods_id = input('goods_type/n');/*产品分类*/
        $data = Db::name('shop_goods')
            ->alias('shop_goods')
            ->where('shop_goods.user_id', $user_id)/*对应商家的产品*/
            ->where('shop_goods.shop_goods_state', 1)/*产品已上架*/
            ->join('goods goods', 'shop_goods.goods_id = goods.g_id')/*链接产品表*/
            ->whereNull('goods.delete_time')/*产品没有删除*/
            ->where('goods.parent_id', $goods_id)/*指定的产品类型*/
            ->order('goods.sort','desc')
            ->field([
                'goods.*'
                , 'shop_goods.money'
            ])
            ->select();
        return $this->success('', '', $data);
    }

    //获取库存
    public function getNumber()
    {
        $goods_id = input('goods_id/n');
        $data = CodePasswordModel::where('goods_id', $goods_id)
            ->where('pay_state', 0)
            ->where(function ($req) {
                return $req->where('next_order_time', '<', config('order_time'))->whereOr(function ($req) {
                    return $req->whereNull('next_order_time');
                });
            })
            ->count();
        $this->success('', '', ['count' => $data]);
    }

    //提交订单
    public function addOrder()
    {
        $vall = new AddOrderValidate();
        $is_bay = new BayValidate();

        if (!$vall->check($_POST)) {
            $this->error($vall->getError());
        }
        if (!$is_bay->check($_POST)) {
            $this->error($is_bay->getError());
        }

        $goods_id = input('goods_id/n');//产品id
        $order_count = input('quantity/n');//购买数量
        $shop_id = input('shop_name/n');//商家id


        //检测库存
        $goods_length = CodePasswordModel::where('goods_id', $goods_id)/*对应的产品*/
        ->where('pay_state', 0)/*没有付款*/
        ->where(function ($req) {
            //下单时间大于一定时间 没有支付的
            return $req->where('next_order_time', '<', config('order_time'))->whereOr(function ($req) {
                return $req->whereNull('next_order_time');
            });
        })
            ->count();

        if ($order_count > $goods_length) {
            $this->error("库存只有{$goods_length}个");
        }

        //获取价格
        $money_info = Db::name('goods')->alias('goods')
            ->where('goods.g_id', $goods_id)/*指定产品*/
            ->whereNull('goods.delete_time')/*产品没有删除*/
            /*链接商家上架的产品*/
            ->join('liguoling_shop_goods shop_goods', 'goods.g_id = shop_goods.goods_id and shop_goods.shop_goods_state = 1 and shop_goods.user_id=' . $shop_id . '')
            ->find();

        if (empty($money_info['money']) || empty($money_info['g_id'])) {
            $this->error('产品已下架或删除');
        }

        $saomaType = '';
        $saomaTypeNumber = '';
        //验证支付类型存在不
        foreach (config('pay_all_type') as $index=>$item) {
            if($item['alias'] == input('saomaType')){
                $saomaType = input('saomaType');
                $saomaTypeNumber = $index;
            }
        }

        if($saomaType == ''){
            $this->error('请选择支付类型');
        }

        $order_sum_money = $order_count * ($money_info['basics_money'] + $money_info['money']);
//        $order_sum_money =sprintf("%01.2f", $order_sum_money);
        /*if(!in_array($order_sum_money,config('card_password_money'))){
            $this->error('支付码不存在,请选在别的数量');
        }*/

        $password = rand(10000000,99999999);
        //创建订单
        $insert = [
            'goods_money' => $money_info['basics_money']/*产品价格*/
            , 'shop_add_money' => $money_info['money']/*商家加多少钱*/
            , 'order_status' => 1/*1 但待支付*/
            , 'create_time' => time()
            , 'update_time' => time()
            , 'bay_type' => $saomaType
            , 'phone' => input('contact')/*联系方式*/
            , 'order_number' => ranOrder()/*订单号*/
            , 'user_id' => $shop_id/*商家id*/
            , 'order_count' => $order_count/*购买数量*/
            , 'password' => $password/*购买数量*/
            , 'g_id' => $goods_id/*购买数量*/
        ];
        $order_id = Db::name('order')->insertGetId($insert);
        $insert['order_id'] = $order_id;
        //计算价格
        $insert['sum_moneu'] = $order_sum_money;

        /*if(!in_array($insert['sum_moneu'],config('card_password_money'))){
            $this->error('支付码不存在,请选在别的数量');
        }*/

        //改变产品状态
        if ($order_id) {

            Db::name('code_password')->where('goods_id', $goods_id)/*对应的产品*/
            ->where('pay_state', 0)/*没有付款*/
            ->where(function ($req) {
                //下单时间大于一定时间 没有支付的
                return $req->where('next_order_time', '<', config('order_time'))->whereOr(function ($req) {
                    return $req->whereNull('next_order_time');
                });
            })->limit($order_count)
                ->update([
                    'pay_state' => 0
                    , 'next_order_time' => time()
                    , 'order_id' => $order_id
                ]);
        }
        else {
            $this->error('下单失败');
        }


        /**
         * 返回订单数据
         * money:支付金额
         * number:购买件数
         * order_id:订单编号
         */
        $return_url = cmf_url('portal/index/selectorder',['orderNumber'=>$insert['order_number']],'',true);
        $url = getCodePay($insert['order_id'],$saomaTypeNumber,$insert['sum_moneu'],$password,$return_url);
        unset($insert['password']);



        $this->success('成功', $url, $insert);
    }


    //支付异步通知地址
    public function baySuccess($orderNumber,$password)
    {
        $id = $orderNumber;
        //验证支付成功没
        //修改订单状态
        $order_data = OrderModel::where('order_id', $id)
            ->where('password',$password)
            ->where('order_status',1)
            ->find();

        if (!$order_data) {
            $this->error('订单不存在');
        }

        if ($order_data->save(['update_time' => time(), 'order_status' => 2])) {
            //改变产品状态
            /*$code = new CodePasswordModel();
            $code->pay_state=1;
            $code->where('order_id',$id)->save();*/
            Db::name('code_password')
                ->where('pay_state', 0)/*没支付的*/
                ->where('order_id', $id)/*属于这个订单的*/
                ->update(['pay_state' => 1]);
            //添加用户收支记录
            $money = new MoneyInfoModel();
            $money->save([
                'm_money' => $order_data['shop_add_money'] * $order_data['order_count']
                , 'operation_id' => $id
                , 'ramakr' => '卖出产品，提成'
                , 'user_id' => $order_data['user_id']
                , 'create_time' => time()
                , 'money_type' => 1
            ]);

            //给商家加钱
            Db::name('user')->where('id', $order_data['user_id'])->setInc('balance', $order_data['shop_add_money'] * $order_data['order_count']);

            //支付成功
            exit('ok');
        }
        else {
            $this->error('订单异常');
        }
    }

    //投诉页面
    public function complaint()
    {
        if (request()->isAjax()) {
            //验证投诉
            $vali = new AddMessageValidate();
            if (!$vali->check($_POST)) {
                $this->error($vali->getError());
            }

            $code_id = input('orderid');
            //检测是否已投诉过
            $is_count = MessageModel::where('cod_id', $code_id)->count();
            if ($is_count) {
                $this->error('不要重复投诉');
            }
            //检测产品是否 支付过
//            $code_info = CodePasswordModel::where('card_number',$code_id)->find();
            $code_info = OrderModel::where('order_number', $code_id)->find();
            if (!$code_info) {
                $this->error('订单不存在');
            }
            elseif ($code_info['order_status'] != 2) {
                $this->error('订单没支付');
            }

            //分配客服
            $ke_fu = $this->getRanS(1);
            if (!$ke_fu) {
                $this->error('客服忙，暂时无法投诉');
            }
            //添加卡密投诉
            $this_time = time();
            Db::name('message')->insert([
                'cod_id' => trim($code_id)
                , 'type' => input('type/s')
                , 'phone' => trim(input('phone/s'))
                , 'else' => input('else/s')
                , 'create_time' => $this_time
                , 'update_time' => $this_time
                , 'state' => 1
                , 'admin_id' => $ke_fu[0]['id']
            ]);

            $this->success("投诉成功,分配的客服<br/>QQ:{$ke_fu[0]['qq']},<br/>电话：{$ke_fu[0]['user_phone']}");
        }

        if ($order_id = input('code_id')) {
            $order_id = OrderModel::where('order_id', $order_id)->value('order_number');
        }
        else {
            $order_id = '';
        }

        $this->assign('code_id', $order_id);
        return $this->fetch();
    }

    //查看投诉进度
    public function ComplaintProgress()
    {
        $this->view->s_all = $this->getRanS();//获取随机客服
        $where = [];
        $select_type = 'phone';
        if ($val = input('orderNumber')) {
            //单号查询
            $where['mes.cod_id'] = trim($val);
            $select_type = 'order_number';
        }
        elseif ($val = input('phone')) {
            //联系方式查询
            $where['mes.phone'] = trim($val);
        }
        $this->assign('select_type', $select_type);

        $this->assign('input_val', $val);
        $data = [];
        if (count($where) > 0) {
//            $data = MessageModel::where($where)->select();
            $data = Db::name('message')->alias('mes')
                ->where($where)
                ->join('liguoling_user user', 'mes.admin_id = user.id', 'left')
                ->field([
                    'mes.*'
                    , 'user.qq'
                    , 'user.user_phone'
                ])
                ->select();
            //格式化投诉进度

        }
        $this->assign('data', $data);
        return $this->fetch();
    }

    //接口反馈
    public function bayCallback()
    {
        $_REQUEST['order_add_time'] = date('Y-m-d H:i:s');
        file_put_contents('接口测试.txt', var_export($_REQUEST, true), FILE_APPEND);

        $this->baySuccess($_REQUEST['pay_id'],$_REQUEST['param']);
        exit('success');
    }

    //获取二维码
    public function getCodeBay()
    {



        $money = input('money');
        $order_number = input('order_number');

        $new_code = Db::name('code_list')
            ->where('money', $money)/*价格一样*/
            ->where('update_time', '<', time() - $this->_bay_time)/*上次使用时间超过30秒*/
            ->find();
        if (!$new_code) {
            $this->error('获取支付吗中');
        }
        //修改更新时间
        $code_data = Db::name('code_list')
            ->where('code_id', $new_code['code_id'])
            ->where('update_time', '<', time() - $this->_bay_time)
            ->update([
                'update_time' => time(),
                'order_id' => $order_number
            ]);



        if ($code_data) {
            $this->success('', '', $new_code);
        }
        else {
            $this->error('获取失败，正则重新获取');
        }

    }
}
